package com.sun.umbrella.service.shiro.filter;

import com.sun.umbrella.remote.RemoteService;
import com.sun.umbrella.session.ContextHolder;
import com.sun.umbrella.session.SessionContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author Jay
 * @version v1.0
 * @description 表单提交过滤器
 * @date 2017-12-03 22:14
 */
public class ServerFormAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private RemoteService remoteService;

    @Autowired
    private ContextHolder contextHolder;


    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        String url = WebUtils.getPathWithinApplication(WebUtils.toHttp(request));
        if (StringUtils.isEmpty(url)) {
            url = getSuccessUrl();
        }
        WebUtils.redirectToSavedRequest(request, response, url);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        if (subject.isAuthenticated()) {
            Session session = subject.getSession();
            session.setAttribute("principal", token.getPrincipal());
        }
        return super.onLoginSuccess(token, subject, request, response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Session session = subject.getSession();
            String principal = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY).toString();
            SessionContext sessionContext = remoteService.getSessionContext(principal);
            contextHolder.initSessionContext(sessionContext);
        }
        return subject.isAuthenticated();
    }

    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        contextHolder.resetContext();
    }

}
